package App.Controllers;

import App.Exception.PasswordErrorException;
import App.Exception.UserExistException;
import App.Exception.UserNotExistException;
import App.Service.AuthService;
import App.Utils.PoJo.Error;
import App.Utils.PoJo.Success;
import App.Utils.Valiation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.repository.query.Param;
import org.springframework.http.HttpRequest;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * 认证控制器
 * Created by yu on 2017/7/18.
 */
@RestController
@RequestMapping("/auth")
public class AuthController
{
    @Autowired
    AuthService authService;

    @RequestMapping(value = "/register",method = RequestMethod.POST)
    public Object register(@RequestParam(name="email") String email,@RequestParam(name="password") String password)
    {
        String valid=valiator(email,password);
        if(valid!=null)
        {
            return new Error(valid,"ValidError");
        }
        if(authService.existUser(email)){
            return new Error("账号已经存在","UserExistError");
        }
        Long auth_id=authService.register(email,password);
        return new Success(true,auth_id);
    }

    @RequestMapping(value = "/login",method = RequestMethod.POST)
    public Object Login(@RequestParam(name="email") String email, @RequestParam(name="password") String password, HttpSession session)
    {
        String valid=valiator(email,password);
        if(valid!=null)
        {
            return new Error(valid,"ValidError");
        }
        Map<String,Object> res=authService.login(email, password, session);
        if(res.containsKey("success")){
            return new Success(true,res.get("success"));
        }
        else if(res.containsKey("error")){
            return new Error(res.get("error"),res.get("errorType"));
        }
        return new Error("服务器崩了","????");
    }

    private String valiator(String email,String password)
    {
        //Map<String,String> res=new HashMap<>(2);
        if(!Valiation.checkEmail(email))
        {
           return "邮箱不符合格式";
        }
        if(password.length()<6)
        {
            return "密码至少6位";
        }
        return null;
    }

    @RequestMapping("/existUser")
    public Object existUser(@RequestParam("email")String Email)
    {
        if(!Valiation.checkEmail(Email))
        {
            return new Error("邮箱不符合格式","validError");
        }
        else return new Success("checkSuccess",authService.existUser(Email));
    }

}
